package com.promise.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.promise.controller.result.FaultResult;
import com.promise.pojo.Fault;
import com.promise.service.FaultServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@CrossOrigin
@RestController
@RequestMapping("/faults")
public class FaultController {
    @Autowired
    private FaultServiceImpl faultService;


    /**
     * 分页查询记录
     *
     * @param currentPage 当前页码
     * @param pageSize    页面数据条数
     * @param searchData  搜索条件
     * @return RecordResult 分页查询结果
     */
    @PostMapping("/{currentPage}/{pageSize}")
    @ResponseBody
    public FaultResult getFaultByPage(@PathVariable Integer currentPage, @PathVariable Integer pageSize,
                                      @RequestBody Fault searchData) {
        // 查询条件
        LambdaQueryWrapper<Fault> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(!StringUtils.isEmpty(searchData.getFaultDate()),
                        Fault::getFaultDate, searchData.getFaultDate())
                .eq(!StringUtils.isEmpty(searchData.getResult()), Fault::getResult,
                        searchData.getResult())
                .eq(!StringUtils.isEmpty(searchData.getSeverity()), Fault::getSeverity,
                        searchData.getSeverity());

        IPage<Fault> iPage = new Page<>(currentPage, pageSize);
        IPage<Fault> page = faultService.page(iPage, queryWrapper);
        Integer code = page.getRecords() != null ? Code.SUCCESS_CODE : Code.ERROR_CODE;
        String msg = page.getRecords() != null ? "查询成功" : "查询失败";
        Map<String, Object> data = new HashMap<>();
        data.put("pages", page.getPages());
        data.put("currentPage", page.getCurrent());
        data.put("pageSize", page.getSize());
        data.put("faults", page.getRecords());
        data.put("total", page.getTotal());
        return new FaultResult(code, data, msg);
    }


    /**
     * 根据faultId删除
     *
     * @param faultId id
     * @return FaultResult
     */
    @DeleteMapping("delete/{faultId}")
    @ResponseBody
    public FaultResult delete(@PathVariable Integer faultId) {
        boolean flag = faultService.removeById(faultId);
        Integer code = flag ? Code.SUCCESS_CODE : Code.ERROR_CODE;
        String msg = flag ? "删除成功" : "删除失败";
        return new FaultResult(code, flag, msg);
    }


    /**
     * 根据id更新故障记录
     *
     * @param faultId   故障记录的ID
     * @param faultData 更新的故障记录数据
     * @return FaultResult 更新结果
     */
    @PutMapping("update/{faultId}")
    @ResponseBody
    public FaultResult updateFault(@PathVariable Integer faultId, @RequestBody Fault faultData) {
        // 检查传入的faultData是否包含需要更新的字段
        if (faultData == null || faultData.getFaultId() == null || !faultData.getFaultId().equals(faultId)) {
            return new FaultResult(Code.ERROR_CODE, null, "更新失败，无效的故障记录ID或数据");
        }

        // 更新操作
        boolean isUpdated = faultService.updateById(faultData);

        // 构建返回结果
        Integer code = isUpdated ? Code.SUCCESS_CODE : Code.ERROR_CODE;
        String msg = isUpdated ? "更新成功" : "更新失败";
        return new FaultResult(code, isUpdated, msg);
    }

    /**
     * 增加故障记录
     *
     * @param fault 故障对象
     * @return FaultResult 增加结果
     */
    @PostMapping("/add")
    @ResponseBody
    public FaultResult addFault(@RequestBody Fault fault) {
        try {
            boolean result = faultService.save(fault);
            Integer code = result ? Code.SUCCESS_CODE : Code.ERROR_CODE;
            String msg = result ? "增加成功" : "增加失败";
            return new FaultResult(code, result, msg);
        } catch (Exception e) {
            // 异常处理逻辑
            Integer code = Code.ERROR_CODE;
            String msg = "增加过程中发生异常：" + e.getMessage();
            return new FaultResult(code, false, msg);
        }
    }
}
